package org.hcf.data;

import com.baomidou.mybatisplus.extension.service.IService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.hcf.common.util.ClassResolverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.*;

@Slf4j
@Data
@Component
public class SqlHelper {
    static Map<Class<? extends IService>, IService> serviceMap = new HashMap<>();
    static Set<Class<?>> classMap = new HashSet<>();
    //    public static SqlHelper me;
    @Autowired
    ApplicationContext temp;
    static ApplicationContext context;

//    static {
//        init();
//    }

    @PostConstruct
    void init() {
        try {
            Set<Class<?>> classes = ClassResolverUtil.findClasses("org.hcf.data");
            initRepository(classes, classMap);
            context = temp;
//            Network.SQL = this;
//            me = this;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private static void initRepository(Set<Class<?>> classes, Set<Class<?>> map) {
        if (classes.size() > 0) {
            for (Class<?> clazz : classes) {
                if (IService.class.isAssignableFrom(clazz) && clazz.isInterface()) {
                    map.add(clazz);
                }
            }
        }
    }

    public static <T extends IService> T getService(Class<T> cls) {
        T service = (T) serviceMap.get(cls);
        if (service != null) return service;
//        Class<?> serviceClass = classMap.get(cls);
        if (classMap.contains(cls)) {
            service = context.getBean(cls);
            if (service != null) {
                serviceMap.put(cls, service);
                return service;
            }
        }
        return null;
    }

}
